#!/usr/bin/env bash
#
# image-tag determines which version to embed into a built image.
#
# It prefers the following in precedence order:
#
# 1. RELEASE_TAG environment variable
# 2. The Git tag of the current commit (if any)
# 3. The version in the VERSION file, suffixed with -devel plus build
#    information.
set -o errexit
set -o pipefail

VERSION=$(sed -e '/^#/d' -e '/^$/d' VERSION | tr -d '\n')
DETECTED_TAG=$(git describe --match 'v*' --exact-match 2>/dev/null || echo -n "")

if [ ! -z "${RELEASE_TAG}" ]; then
  echo ${RELEASE_TAG}
  exit 0
elif [ ! -z "${DETECTED_TAG}" ]; then
  echo ${DETECTED_TAG}
  exit 0
fi

set -o nounset

if [[ -z $(git status -s) ]]; then
  # There are no changes; report version as VERSION-devel+SHA.
  SHA=$(git rev-parse --short HEAD)
  echo ${VERSION}-devel+${SHA}
else
  # Git is dirty; tag as VERSION-devel+dirty.
  echo ${VERSION}-devel+dirty
fi
